﻿using AutoMapper;
using ManagementApi.Models;
using ManagementApi.Models.Cms;
using ManagementApi.Models.WeiXin;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules.Cms;
using Modules.Cms.Entitys;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Exceptions;
using System.ComponentModel.DataAnnotations;

namespace ManagementApi.Controllers.WeiXin;

/// <summary>
/// 订单管理
/// </summary>
[Route("/api/v1/order")]
[ApiController]
[Authorize]
public class OrderController : ControllerBase
{
    private readonly IMapper mapper;
    private readonly IApplicationContext applicationContext;
    private readonly CmsDealerService cmsDealerService;
    private readonly CmsOrderService orderService;
    private readonly CmsCustomLeaseService customLeaseService;
    private readonly CmsCustomService customService;

    private readonly int dealerId;

    public OrderController(IMapper mapper, IApplicationContext applicationContext, CmsDealerService cmsDealerService, CmsOrderService orderService, CmsCustomLeaseService customLeaseService, CmsCustomService customService)
    {
        this.mapper = mapper;
        this.applicationContext = applicationContext;
        this.cmsDealerService = cmsDealerService;
        this.orderService = orderService;
        this.customLeaseService = customLeaseService;
        this.customService = customService;
        //查询当前登录人经销商ID
        CmsDealer? cmsDealer = cmsDealerService.GetDalerByUserId(applicationContext.CurrentUser?.Id ?? 0);
        if (cmsDealer == null)
            throw new BusinessException($"当前登录人还没有绑定经销商，请联系管理员");
        dealerId = cmsDealer.Id;

    }

    /// <summary>
    /// 查询我的订单数量
    /// </summary>
    /// <returns></returns>
    [HttpGet("getOrder")]
    public ApiResult<OrderDto> GetOrder()
    {
        OrderDto dto = new();
        //查询我的气罐总数,发货单-退货单
        var cmsOrders = orderService.GetOrdersByDealerId(dealerId).Where(t => t.ConsigneeStatus == 20);
        //查询已租气瓶
        var customLeases = customLeaseService.GetCmsCustomLeasesByDealerId(dealerId).Where(t => t.Status == 10);
        if (cmsOrders.Any())
        {
            int inCount = cmsOrders.Where(t => t.Type == 20).Sum(t => t.OutboundQty) ?? 0;
            int outCount = cmsOrders.Where(t => t.Type == 10).Sum(t => t.OutboundQty) ?? 0;
            dto.AllCount = outCount - inCount;
            dto.UsedCount = customLeases.Count();
            dto.HasCount = dto.AllCount - dto.UsedCount;
        }
        return ApiResult<OrderDto>.Success(dto);
    }

    /// <summary>
    /// 查询已租赁列表
    /// </summary>
    /// <param name="query"></param>
    /// <param name="pageNum"></param>
    /// <param name="pageSize"></param>
    /// <returns></returns>
    [HttpGet("getCmsCustomLeases")]
    public ApiResult<PageDto<CmsCustomLeaseDto>> GetCmsCustomLeases([FromQuery] CmsCustomLeaseQuery query, int pageNum = 1, int pageSize = 20)
    {
        query.Status = 10;
        var roles = customLeaseService.GetPages(query, pageNum, pageSize);
        var dtos = roles.AsPageDto(source => { return source.AsDto(); });
        return ApiResult<PageDto<CmsCustomLeaseDto>>.Success(dtos);
    }

    /// <summary>
    /// 退租
    /// </summary>
    /// <param name="form"></param>
    /// <returns></returns>
    [HttpPost("returnLease")]
    public ApiResult ReturnLease(ReturnLeaseForm form)
    {
        var entity = customLeaseService.Get(form.Id);
        if (entity == null) return ApiResult.Failure("数据不存在");
        entity.ReturnDt = form.ReturnDt;
        entity.ReturnAmount = form.ReturnAmount;
        entity.Status = 20;
        entity.DealerId = dealerId;
        customLeaseService.Update(entity);
        return ApiResult.Success("操作成功");
    }

    /// <summary>
    /// 租赁
    /// </summary>
    /// <param name="form"></param>
    /// <returns></returns>
    [HttpPost("createLease")]
    public ApiResult CreateLease(CreateLeaseForm form)
    {
        CmsCustom? cmsCustom = customService.Get(form.CustomId ?? 0);
        if (cmsCustom == null)
        {
            cmsCustom = new CmsCustom()
            {
                Name = form.Name,
                Phone = form.Phone,
                CardNo = form.CardNo,
                Address = form.Address ?? "",
                CreateDt = DateTime.Now,
                DealerId = dealerId,
                CreateUserId = applicationContext.CurrentUser?.Id ?? 0,
                CreateUserName = applicationContext.CurrentUser?.Name ?? ""
            };
            customService.Create(cmsCustom);
        }
        CmsCustomLease entity = mapper.Map<CmsCustomLease>(form);
        entity.CreateDt = DateTime.Now;
        entity.CreateUserId = applicationContext.CurrentUser?.Id ?? 0;
        entity.CreateUserName = applicationContext.CurrentUser?.Name ?? "";
        entity.Status = 10;
        entity.CustomId = cmsCustom.Id;
        entity.DealerId = dealerId;

        customLeaseService.Create(entity);
        return ApiResult.Success("操作成功");
    }

    /// <summary>
    /// 根据客户关键字查询客户信息
    /// </summary>
    /// <param name="keywords"></param>
    /// <returns></returns>
    [HttpGet("GetCustomByName")]
    public ApiResult<CmsCustomDto> GetCustomByName([Required(ErrorMessage = "客户信息不能为空")] string keywords)
    {
        CmsCustom? cmsCustom = customService.GetCustomByKeywords(keywords);
        if (cmsCustom == null) return ApiResult<CmsCustomDto>.Success(new CmsCustomDto());
        CmsCustomDto dto = mapper.Map<CmsCustomDto>(cmsCustom);
        return ApiResult<CmsCustomDto>.Success(dto);
    }

    /// <summary>
    /// 查询发货单列表
    /// </summary>
    /// <returns></returns>
    [HttpGet("getOrderList")]
    public ApiResult<PageDto<CmsOrderDto>> GetOrderList([FromQuery] CmsOrderQuery query, int pageNum = 1, int pageSize = 20)
    {
        query.DealerId = dealerId;
        var data = orderService.GetPages(query, pageNum, pageSize);
        var dtos = data.AsPageDto(source => { return source.AsDto(); });
        return ApiResult<PageDto<CmsOrderDto>>.Success(dtos);
    }

    /// <summary>
    /// 收货
    /// </summary>
    /// <param name="form"></param>
    /// <returns></returns>
    [HttpPost("returnOrder")]
    public ApiResult ReturnOrder(CmsReturnOrderForm form)
    {
        CmsOrder? entity = orderService.Get(form.Id);
        if (entity == null) return ApiResult.Failure("数据不存在");
        entity.ConsigneeStatus = 20;
        entity.ConsigneeDt = form.ConsigneeDt;
        entity.Consignee = form.Consignee;
        orderService.Update(entity);
        return ApiResult.Success("操作成功");
    }

    /// <summary>
    /// 创建发货单
    /// </summary>
    /// <param name="form"></param>
    /// <returns></returns>
    [HttpPost("create")]
    public ApiResult Add(CmsOrderEditForm form)
    {
        CmsOrder entity = new CmsOrder();
        mapper.Map(form, entity);
        entity.CreateDt = DateTime.Now;
        entity.CreateUserId = applicationContext.CurrentUser?.Id ?? 0;
        entity.CreateUserName = applicationContext.CurrentUser?.Name ?? "";
        entity.Type = 20;
        entity.ConsigneeStatus = 10;
        entity.BillNo = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        entity.DealerId = dealerId;
        orderService.Create(entity);
        return ApiResult.Success("创建成功");
    }

}
